<?php
class Khuyenmai extends Model
{

    public function getKhuyenMai()
    {
        return $this->Db->run("select km_id, km_ten, DATE_FORMAT(km_ngaybd,'%d/%m/%y')as batdau,DATE_FORMAT(km_ngaykt,'%d/%m/%y') as ketthuc from quatangkm where NOW() BETWEEN km_ngaybd AND km_ngaykt  union select km_id, km_ten, DATE_FORMAT(km_ngaybd,'%d/%m/%y')as batdau,DATE_FORMAT(km_ngaykt,'%d/%m/%y') as ketthuc from giatrikm  where NOW() BETWEEN km_ngaybd AND km_ngaykt ORDER BY km_id ASC");
    }

    public function getChiTietkm($id, &$giatri)
    {
        $data = $this->Db->select('giatrikm', 'km_id = :id1', array('id1' => $id));

        #khuyen mai gia tri
        if (count($data) > 0) {
            $giatri = true;
            $sanpham = $this->Db->run("select dt_id, dt_ten, dt_gia, ctgtkm_giatri, (dt_gia-ctgtkm_giatri) as giagiam from chitietgiatrikm ct  NATURAL JOIN dienthoai dt  where km_id= :id ",
                array('id' => $id));
            foreach ($sanpham as &$item) {
                $item['dt_gia_fo'] = App::formatVnd($item['dt_gia']);
                $item['ctgtkm_giatri_fo'] = App::formatVnd($item['ctgtkm_giatri']);
                $item['giagiam_fo'] = App::formatVnd($item['giagiam']);
            }

            App::log($sanpham);
            return $sanpham;
        }
        #Khuyen mai san pham
        else {
            $giatri = false;

            $dienthoai = new Dienthoai();

            $sanpham = $this->Db->run("select * from chitietquatangkm ct NATURAL join dienthoai dt WHERE km_id = :id",
                array('id' => $id));
            # get dienthoai's image url
            foreach ($sanpham as &$item) {
                $item['h_url'] = $dienthoai->getDienthoaiFirstImage($item['dt_id']);
                $item['dt_gia_fo'] = App::formatVnd($item['dt_gia']);

                # get quatang
                $gifts = $this->Db->run('SELECT * FROM chitietqt ct NATURAL JOIN quatang qt WHERE km_id = :km_id ' .
                    'AND dt_id = :dt_id', array('km_id' => $id, 'dt_id' => $item['dt_id']));
                foreach ($gifts as &$gift)
                {
                    $gift['qt_giatri_fo'] = App::formatVnd($gift['qt_giatri']);
                }
                $item['gifts'] = $gifts;


            }

            return $sanpham;
        }
    }

    public function getTenKm($id)
    {
        $data = $this->Db->executeScalar('SELECT km_ten FROM giatrikm WHERE km_id = :id', array('id' => $id));
        $data || $data = $this->Db->executeScalar('SELECT km_ten FROM quatangkm WHERE km_id = :id', array('id' => $id));

        return $data;
    }
}